<template>
  <a-modal
    :visible="visible"
    :title="$t('机位报表')"
    :width="width"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    class="customHeight customHeightChild modal_title"
    v-drag
  >
    <template slot="footer">
      <a-button @click="handleCancel" :loading="confirmLoading">{{$t('关闭')}}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item :label="$t('时间')">
                <a-date-picker
                  :show-time="true"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择开始时间')"
                  class="query-group-cust"
                  v-model="info.createTime_begin"
                ></a-date-picker>
                <span class="query-group-split-cust"></span>
                <a-date-picker
                  :show-time="true"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  :placeholder="$t('请选择结束时间')"
                  class="query-group-cust"
                  v-model="info.createTime_end"
                ></a-date-picker>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('项目分类')">
                <a-tree-select
                  allowClear
                  v-model="info.gameTypeId"
                  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="gameTypeList"
                  :placeholder="$t('请选择')"
                />
                <!-- <a-select v-model="info.gameTypeId">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in gameTypeList">{{
                    item.name
                  }}</a-select-option>
                </a-select> -->
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('项目名称')">
                <a-select v-model="info.gameId">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in gameList">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col>
              <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">{{$t('查询')}}</a-button>
                <a-button type="primary" style="margin-left: 8px" @click="handleExportXls($t('机位报表'))"
                  >{{$t('导出')}}</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :customHeaderRow="customHeaderRow"
          :customRow="customRow"
          class="j-table-force-nowrap"
        >
        </a-table>
      </div>
    </a-spin>
  </a-modal>
</template>
<script>
import { getAction, downFile } from '@/api/manage'
export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      width: 1250,
      columns: [],
      dataSource: [],
      info: {},
      gameTypeList: [],
      gameList: [],
      hideColumns:"",
      selectedRowIndex: []
    }
  },
  methods: {
    initDictConfig() {
      this.selectedRowIndex = []
      this.dataSource = []
      getAction('/game/bisGame/list',{pageSize: 9999}).then((res) => {
        if (res.success) {
          this.gameList = res.result.records
          this.gameList.unshift({ id: '', name: this.$t('全部') })
        }
      })
      getAction('/game/bisGameType/rootList', { pageSize: 1000 }).then((res) => {
        if (res.success) {
          let list = res.result.records
          if (list.length > 0) {
            list.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                this.getHasChild(col)
              }
            })
            this.gameTypeList = this.getDataByResult(list)
            this.gameTypeList.unshift({ key: '', id: '', value: '', title: this.$t('全部') })
          }
        }
      })
    },
    getHasChild(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      query.consumeType = 1
      getAction('/game/bisGameType/childList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChild(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.gameTypeList = [...that.gameTypeList]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    show(record, columns) {
      this.hideColumns = record.hideColumns
      this.initDictConfig();
      this.columns = columns.map(c=>{
        let dtl = Object.assign({}, c)
        if(dtl.dataIndex == 'gameId_dictText'){
          delete dtl.customRender
        }
        delete dtl.width
        return dtl
      })
      this.columns.splice(this.columns.length-1,1)
      this.columns.unshift({
        title: this.$t('项目分类'),
        align: 'center',
        dataIndex: 'gameTypeId_dictText',
      })
      let x = this.columns.findIndex(c=>{
        return c.dataIndex == 'gameId_dictText'
      })
      if(x>-1){
        this.columns.splice(x+1,0,{
          title: this.$t('设备编码'),
          align: 'center',
          dataIndex: 'deviceId',
        },
        {
          title: this.$t('设备名称'),
          align: 'center',
          dataIndex: 'deviceId_dictText',
        },
        {
          title: this.$t('机号'),
          align: 'center',
          dataIndex: 'machineNo',
        })
      }else{
        this.columns.splice(1,0,{
          title: this.$t('设备编码'),
          align: 'center',
          dataIndex: 'deviceId',
        },
        {
          title: this.$t('设备名称'),
          align: 'center',
          dataIndex: 'deviceId_dictText',
        },
        {
          title: this.$t('机号'),
          align: 'center',
          dataIndex: 'machineNo',
        })
      }
      this.visible = true
      this.info = Object.assign({}, record)
      this.searchQuery();
    },
    customHeaderRow(){
      return {
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word'
        }
      }
    },
    customRow(r, i) {
      return {
        on: {
          click: () => {
            let x = this.selectedRowIndex.findIndex(r=>{return r=='a'+i})
            if( x == -1 ){
              this.selectedRowIndex.push('a'+i)
            }else{
              this.selectedRowIndex.splice(x, 1)
            }
          }
        },
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word',
          backgroundColor: this.selectedRowIndex.findIndex(r=>{return r=='a'+i}) > -1 ? '#FFECE6' : '',
          fontWeight: r.deviceId == this.$t('合计') ? 700 : 400,
        },
      }
    },
    searchQuery() {
      this.selectedRowIndex = []
      let query = {
        createTime_begin:this.info.createTime_begin,
        createTime_end:this.info.createTime_end,
        gameId: this.info.gameId,
        gameTypeId: this.info.gameTypeId,
        groupBy: 'game_type_id,game_id,device_id,machine_no',
        outputType: this.info.outputType,
      }
      this.confirmLoading = true
      getAction('/game/bisGameCoinRecord/getReport', query)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.dataSource.forEach(col=>{
                if(col.deviceId == null){
                  col.deviceId = this.$t('合计')
                }
            })
          }else{
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let query = {
        createTime_begin:this.info.createTime_begin,
        createTime_end:this.info.createTime_end,
        gameId: this.info.gameId,
        gameTypeId: this.info.gameTypeId,
        groupBy: 'game_type_id,game_id,device_id,machine_no',
        outputType: this.info.outputType,
        hideColumns: this.hideColumns
      }
      downFile('/game/bisGameCoinRecord/exportReportXls', query).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
  },
}
</script>